<?php
/**
 * Created by PhpStorm.
 * User: mac
 * Date: 2018/4/18
 * Time: 下午6:33
 */

class CreteProcess
{
    public $mpid = 0;

    public $works = [];

    public $max_precess = 10;

    public $new_index = 0;

    public $index = 0;

    public $host = '127.0.0.1';

    public $port = 6379;

    public $dbhost = '127.0.0.1';  // mysql服务器主机地址

    public $dbuser = 'hwj';            // mysql用户名

    public $dbpass = 'hwj199601';          // mysql password


    public function __construct(){
        try {
            //$this->setData();
            $this->mpid = posix_getpid();
            $this->run();
            $this->processWait();
        }catch (\Exception $e){
            die('ALL ERROR: '.$e->getMessage());
        }
    }

    public function run(){
        for ($i=0; $i < $this->max_precess; $i++) {
            $this->CreateProcess($this->new_index);
            $this->new_index++;
        }
    }

    public function CreateProcess($index=null){
        $process = new swoole_process(function(swoole_process $worker)use($index){
            swoole_set_process_name(sprintf('php-ps:%s',$index));
            $str = $worker->pid . '----' . $this->getData();
            echo "$str\n";
            sleep(1);
        }, false, false);
        $pid=$process->start();
        $this->works[$index]=$pid;
        return $pid;
    }

    public function setData()
    {
        $redis = new Redis();
        $redis->connect($this->host, $this->port);
        $redis->lPush('array', 1, 2, 3, 4, 5, 6);
    }

    public function getData()
    {
        $redis = new Redis();
        $redis->connect($this->host, $this->port);
        $value = $redis->lPop('array');
        if (!empty($value)) {
            $value = $this->pushDataToMysql($value);
        }
        return $value;
    }

    function pushDataToMysql($city)
    {
        $dizhi = $city;
        $str = file_get_contents('./address/'.$dizhi.'.txt');
        $arr = explode("\n", $str);
        $temp_arr = array();
        foreach ($arr as $v) {
            $temp_arr[] = explode("\t", $v);
        }
        #unset($temp_arr[11334]);
        #print_r($temp_arr[1569]);
        #die();

        $conn = mysqli_connect($this->dbhost, $this->dbuser, $this->dbpass);
        mysqli_query($conn, "set names utf8");
        mysqli_select_db( $conn, 'dev' );
        mysqli_query($conn, "SET AUTOCOMMIT=0"); // 设置为不自动提交，因为MYSQL默认立即执行
        mysqli_begin_transaction($conn);    // 开始事务定义

        $time = time();
        $zh = 0;
        foreach($temp_arr as $v) {
            $name = addslashes($v[2]);
            $room_count = empty($v[3]) ? '' : addslashes($v[3]);
            $telephone = empty($v[4]) ? '' : addslashes($v[4]);
            $city = empty($v[5]) ? '' : addslashes($v[5]);
            $qu = empty($v[6]) ? '' : addslashes($v[6]);
            $address = empty($v[7]) ? '' : addslashes($v[7]);
            $class = empty($v[8]) ? '' : addslashes($v[8]);
            $liansuo = empty($v[9]) ? '' : addslashes($v[9]);
            $kaiye = empty($v[10]) ? '' : addslashes($v[10]);
            $zhuangxiu = empty($v[11]) ? '' : addslashes($v[11]);
            $url = 'http://restapi.amap.com/v3/geocode/geo?key=de5fb056635efe79e01afbe47d1563de&address='.$name.'&city='.$city;
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_HEADER, false);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
            $gaode_res = curl_exec($curl);
            curl_close($curl);
            if (!$gaode_res) {
                file_put_contents('./fail/'.$dizhi.'_error.log', "$zh \n", FILE_APPEND);
                file_put_contents('./data.log', "$zh yichang\n", FILE_APPEND);
                continue;
            }
            $gaode_arr = json_decode($gaode_res, true);
            $count = count($gaode_arr['geocodes']);
            if ($count != 0) {
                $ad_code = $gaode_arr['geocodes'][0]['adcode'];
                $district = is_array($gaode_arr['geocodes'][0]['district']) ? '' : $gaode_arr['geocodes'][0]['district'];
                $jingwei = explode(',', $gaode_arr['geocodes'][0]['location']);
                $lat = $jingwei[1];
                $lng = $jingwei[0];
            } else {
                $ad_code = 0;
                $lat = '';
                $lng = '';
                $district = '';
            }
            //echo "district value is $district\n";
            //die();
            $sql = "insert into jiudian values(null, '".$name."', '".$room_count."', '".$telephone."', '".$city."', '".$qu."', '".$address."', '".$class."', '".$liansuo."', '".$kaiye."', '".$zhuangxiu."', null, null, '".$ad_code."', '".$lat."', '".$lng."', 0, '".$district."')";
            $res = mysqli_query($conn, $sql);
            if (!$res) {
                file_put_contents('./data.log', "$zh error\n", FILE_APPEND);
                mysqli_query($conn, "ROLLBACK");     // 判断当执行失败时回滚
                die();
            } else {
                file_put_contents('./data.log', "$zh success\n", FILE_APPEND);
            }
            $zh++;
        }
        mysqli_commit($conn);            //执行事务
        mysqli_close($conn);
        $zh = round((time() - $time) / 60, 2);
        $result =  "$dizhi 写入完成耗时 $zh 分钟 \r\n";
        return $result;
    }

    public function rebootProcess($ret){
        $pid=$ret['pid'];
        $index=array_search($pid, $this->works);
        if($index!==false){
            $index=intval($index);
            $new_pid=$this->CreateProcess($index);
            echo "rebootProcess: {$index}={$new_pid} Done\n";
            return;
        }
        throw new \Exception('rebootProcess Error: no pid');
    }

    public function processWait(){
        while(1) {
            if(count($this->works)){
                $ret = swoole_process::wait();
                if ($ret) {
                    $this->rebootProcess($ret);
                }
            }else{
                break;
            }
        }
    }
}
